package com.ying.dogying.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ying.dogying.dao.EsDao;
import com.ying.dogying.entity.dto.ImPostDto;
import com.ying.dogying.es.dto.EsPostDto;
import com.ying.dogying.service.EsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private EsDao esDao;

    @Override
    public IPage<EsPostDto> selectByParams(Page page, String keyword) {
        // mybatis plus的page——转成——>jpa的page
        Pageable pageable = PageRequest.of(Math.toIntExact(page.getCurrent() - 1), Math.toIntExact(page.getSize()));
        // 搜索es得到pageData
        org.springframework.data.domain.Page<EsPostDto> search = esDao.findByTitleOrContentLike(keyword, keyword, pageable);
        // jpa的pageData——转成——>mybatis plus的pageData
        IPage pageData = new Page(page.getCurrent(), page.getSize(), search.getTotalElements());
        pageData.setRecords(search.getContent());
        return pageData;
    }

    @Override
    public int initEsSearch(List<ImPostDto> records) {
        if(null == records || records.isEmpty()) {
            return 0;
        }
        List<EsPostDto> list = Lists.newArrayList();
        for(ImPostDto imPostDto : records) {
            EsPostDto esPostDto = BeanUtil.copyProperties(imPostDto, EsPostDto.class);
            list.add(esPostDto);
        }
        esDao.saveAll(list);
        return list.size();
    }
}
